package net.wang.totakecodenotes.wechatofficaccounts.utils;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件工具类
 */
public class FileUtils {
    public static String FILE_SERVER_PATH;
    public static String IMAGE_FOLDER_PATH = "/to_take_code_notes_files/image/";

    private static final Logger logger = Logger.getLogger(FileUtils.class);

    static {
        FILE_SERVER_PATH = OSUtils.isWindowsWin10() ? "E:/Servers/tomcat_file/webapps/" : "/mnt/dev_home/servers/tomcat_03_8089_file/webapps";
    }

    private static String buildFolder() {
        String folderName = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        logger.info(FILE_SERVER_PATH + IMAGE_FOLDER_PATH + folderName);
        File folder = new File(FILE_SERVER_PATH + IMAGE_FOLDER_PATH + folderName);

        if (!folder.exists()) {
            folder.mkdirs();
        }

        return folder.toString();
    }

    /**
     * 下载微信媒体文件
     *
     * @param mediaId    媒体文件Id
     * @param requestUrl 下载地址
     * @return
     * @throws IOException
     */
    public static String getWeiXinFile(String mediaId, String requestUrl) throws IOException {
        String filePath;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        try {
            URL url = new URL(requestUrl);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            // 根据内容类型获取扩展名
            String fileExt = conn.getHeaderField("Content-Type");
            // 将mediaId作为文件名
            filePath = buildFolder() + mediaId + fileExt;

            bis = new BufferedInputStream(conn.getInputStream());

            fos = new FileOutputStream(new File(filePath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            conn.connect();
            String info = String.format("下载媒体文件成功，filePath=" + filePath);
            logger.info(info);
        } catch (Exception e) {
            filePath = null;
            String error = String.format("下载媒体文件失败：%s", e);
            logger.info(error);
        } finally {
            fos.close();
            bis.close();
        }
        return filePath;

    }
}